/**
 * 省市区选择
 * @author     Quentin
 * @since      2015/9/7 17:03
 * @copyright  CHOFN
 * @version    3.3.0.0
 */

!(function ($) {

    if (typeof $.fn.multilevelSelect == 'function') {
        return;
    }

    var dataTree;

    $.fn.multilevelSelect = function (opts) {
        //默认配置
        var options = {
            names: [],
            selected : [],
            disabled : false,
            url: '/ajax/getarea'
        };
        opts = $.extend(options, opts);
        var topLevelId = opts.names[0],
            self       = this,
            data       = opts.data;

        if(dataTree === undefined && opts.url) {
            $.get(opts.url, function (res) {
                data = res;
                dataTree = res;
                init();
            }, 'json');
        } else {
            data = dataTree;
            init();
        }

        function init() {
            appendSelect(topLevelId, data, opts.selected[0]);
        }

        function appendSelect(id, options, selected) {
            $('<select style="margin-right:5px;" id="' + id + '" name="' + id + '" '+(opts.disabled ? 'disabled' : '')+'></select>').appendTo(self);
            var optionsHTML = '<option value="">-请选择-</option>';
            for (var key in options) {
                optionsHTML += '<option value="'+options[key].id+'" '+(selected == options[key].id ? 'selected' : '')+'>'+options[key].name+'</option>'
            }
            $('#'+id).append(optionsHTML);
            if (selected) {
                var index = $('#'+id).index();
                var nextNodeData;
                $(self).find('select:lt('+(index+1)+')').each(function () {
                    nextNodeData = nextNodeData ? nextNodeData[$(this).val()]['kids'] : data[$(this).val()]['kids'];
                });
                nextNodeData.length !== 0 && appendSelect(opts.names[index+1], nextNodeData, opts.selected[index+1]);
            }
        }

        $(self).delegate('select', 'change', function () {
            var index = $(this).index();
            var nextLevel = opts.names[index+1];
            var nextNodeData;
            var value = parseInt($(this).val());

            $(self).find('select:gt('+index+')').remove();
            if (isNaN(value)) {
                return;
            }

            $(self).find('select:lt('+(index+1)+')').each(function () {
                nextNodeData = nextNodeData ? nextNodeData[$(this).val()]['kids'] : data[$(this).val()]['kids'];
            });

            if (nextLevel != undefined && nextNodeData.length !== 0) {
                appendSelect(nextLevel, nextNodeData);
            }
        });
    }

})(jQuery);